<template>
  <div class="chat-item">
    <div class="chat-list" v-for="(message, index) in props.AI_OutList" :key="index">
      <div :class="['chat-dialog', message.role === 'user' ? 'user-message' : 'ai-message']">
        <template v-if="message.role === 'user'">
          {{ message.content }}
        </template>
        <template v-else>
          <div v-if="message.content">
            <!-- 添加调试输出 -->            
            <MdPreview 
              v-model="message.content" 
              :preview-only="true"
              ref="mdPreview"
            />
          </div>
          <div v-else class="loading">加载中...</div>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup>
import { MdPreview } from "md-editor-v3";
import { ref, watch, nextTick, onMounted } from "vue";
import "md-editor-v3/lib/preview.css";

const props = defineProps({
  AI_OutList: {
    type: Array,
    required: true,
    default: () => []
  },
});

const previewTheme = ref("default");

// 监听消息列表变化
watch(() => props.AI_OutList, (newList) => {
  if (newList && newList.length > 0) {
    props.AI_OutList = newList;
  }
}, { deep: true, immediate: true });

</script>

<style scoped>
.chat-item {
  width: 100%;
  display: flex;
  flex-direction: column; /* 子元素垂直排列 */
}

::v-deep .v-note-wrapper {
  min-height: 60px;
}

.chat-list {
  display: flex;
  flex-direction: column; /* 子元素垂直排列 */
  align-items: flex-end; /* 让聊天项靠右对齐 */
  width: 100%;
}

.user-message {
  display: flex;
  justify-content: flex-end; /* 保持靠右 */
  max-width: 60%; /* 限制最大宽度为60% */
  min-width: 0; /* 允许内容宽度小于容器宽度 */
  padding: 8px;
  border-radius: 6px;
  background-color: #3d65f7;
  color: #ffffff;
  margin-bottom: 10px;
  word-wrap: break-word; /* 允许内容在达到最大宽度时换行 */
  overflow-wrap: break-word; /* 允许在长单词或URL内部进行换行 */
}

.ai-message {
  width: calc(100% - 6px);
  background-color: #f0f0f0;
  padding: 3px;
  border-radius: 6px;
  margin-bottom: 10px;
  text-align: left;
  word-wrap: break-word; /* 允许内容在达到最大宽度时换行 */
  overflow-wrap: break-word; /* 允许在长单词或URL内部进行换行 */
  align-self: flex-start; /* 让AI消息靠左对齐 */
}

.loading {
  padding: 10px;
  color: #666;
  font-style: italic;
}

.markdown-preview {
  width: 100%;
  overflow: hidden;
  min-height: 20px;
}

.markdown-preview :deep(.md-editor-preview) {
  padding: 8px;
  background: transparent;
  font-size: 14px;
  line-height: 1.6;
}

/* 优化代码块显示 */
:deep(.md-editor-preview pre) {
  background-color: #f8f8f8 !important;
  border-radius: 4px;
  padding: 12px;
  margin: 8px 0;
}

/* 优化链接样式 */
:deep(.md-editor-preview a) {
  color: #3d65f7;
  text-decoration: none;
}

:deep(.md-editor-preview a:hover) {
  text-decoration: underline;
}

/* 优化表格样式 */
:deep(.md-editor-preview table) {
  border-collapse: collapse;
  width: 100%;
  margin: 8px 0;
}

:deep(.md-editor-preview th),
:deep(.md-editor-preview td) {
  border: 1px solid #ddd;
  padding: 8px;
}

:deep(.md-editor-preview-wrapper) {
  background: transparent !important;
}
</style>